<template>
  <div class="main">
    <el-card>
      <div class="upload-test-group">
        <el-divider content-position="left">第二步 测试集上传</el-divider>
        <el-form ref="uploadForm" class="upload-form">
          <el-form-item label="类型选择">
            <el-select v-model="type" placeholder="请选择类型">
              <el-option label="JSON" value="1"></el-option>
              <el-option label="URL" value="2"></el-option>
              <el-option label="文件上传" value="3"></el-option>
            </el-select>
          </el-form-item>
          <!-- 动态渲染输入框或文件上传组件 -->
          <el-form-item v-if="type === '1' || type === '2'" label="内容">
            <el-input v-model="content" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item v-if="type === '3'" label="上传文件">
            <el-upload
                class="upload-demo"
                drag
                ref="uploadRef"
                :headers="{'Problem-Id': problemId}"
                :before-upload="beforeUpload"
                :auto-upload="false"
                :on-change="handleFileChange"
                :file="file">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只支持单个.json文件</div>
            </el-upload>
          </el-form-item>

          <el-button size="large" class="next2" type="primary" @click="submitData">下一步</el-button>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue';
import { ElMessage } from 'element-plus';
import axios from "axios";
import router from "@/router";
import {useStore} from "vuex";


const store = useStore();
const problemId = computed(() => store.state.problemId);


const type = ref('3');
const content = ref('');
const fileList = ref([]);  // 初始为空数组

function beforeUpload(file) {
  const isJSON = file.type === 'application/json';
  if (!isJSON) {
    ElMessage.error('上传文件只能是 JSON 类型!');
    return false;
  }
  return true;
}

function handleFileChange(file, newFileList) {
  // 仅保留最新上传的文件
  fileList.value = [newFileList[newFileList.length - 1]]; // 存储最后一个选中的文件，即最新的文件
}

async function submitData() {
  if (type.value === '3' && fileList.value.length === 0) {
    ElMessage.error('请先选择一个文件');
    return;
  }

  let url = `/oj/ProblemsGroup/problems/uploadTestGroup`;
  let payload;

  if (type.value === '3') {
    const file = fileList.value[0];
    const formData = new FormData();
    formData.append('file', file.raw); // 确保文件的 `raw` 属性包含文件实际内容
    formData.append('type', 'file');
    formData.append('problemId', problemId.value);
    payload = formData;
    await uploadFile(url, payload);
  } else {
    // 处理其他数据类型的提交逻辑
  }
}

async function uploadFile(url, formData) {
  try {
    const response = await axios.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    if (response.data.code === 200) {
      ElMessage.success('测试集上传成功!');
      await store.dispatch('updateTestGroupMongoId', response.data.data.id);
      await store.dispatch('updateTestGroupId', response.data.data.testGroupId);
      await router.push('/student/oj/UploadCode');
    } else {
      ElMessage.error(`提交失败: ${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error('网络错误或服务器故障');
  }
}
</script>




<style scoped>
.next2 {
  margin-top: 20px;
  margin-bottom: 20px;
  float: right;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  margin: 2.5vh auto;
}

.upload-demo {
  width: 100%;
}
.upload-demo i {
  color: #409EFF;
  font-size: 42px;
  vertical-align: middle;
}

.upload-demo .el-upload__text {
  display: block;
  font-size: 14px;
  color: #666;
}

.upload-demo .el-upload__tip {
  font-size: 12px;
  color: #999;
  line-height: 1.5;
  padding-top: 10px;
}

.upload-form {
  width: 100%;
  height: 100%;
}
</style>
